import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import { ElMessage } from "element-plus";

// 定义返回值类型
// 与后端ResultVo一致
export interface Result<T = any> {
  code: number;
  msg: string;
  data: T;
}

// axios 请求配置
const config: AxiosRequestConfig = {
  // baseURL: "http://localhost:8089",
  baseURL: process.env.BASE_API,
  
  // baseURL: "/api",
  timeout: 10000, // 超时时间 
  withCredentials: true, // 允许携带cookie
};

// HTTP 类
class Http {
  private instance: AxiosInstance;
  // 构造函数
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.interceptors();
  }

  // 定义拦截器
  private interceptors() {
    // 请求拦截器,axios发送请求之前的处理
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // 请求头部携带 token
        // let token = sessionStorage.getItem("token") || "";
        let token = "";
        if (token) {
          config.headers!["token"] = token;
        }
        // console.log("Request Config:", config);
        return config;
      },
      (error: any) => {
        error.data = {};
        error.data.msg = "请求超时";
        return error;
      }
    );

    // 响应拦截器,axios收到响应之后的处理
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        console.log("Response Data:", response.data.code);
        if (response.data && response.data.code !== 200) {
          ElMessage.error(response.data.msg || "请求失败");
          return Promise.reject(response.data);
        }
        return response.data; // 返回响应数据
      },
      (error) => {
        let errorMsg = "连接错误";
        if (error.response) {
          switch (error.response.status) {
            case 400:
              errorMsg = "请求参数错误";
              break;
            case 401:
              errorMsg = "未授权，请登录";
              break;
            case 403:
              errorMsg = "拒绝访问";
              break;
            case 404:
              errorMsg = "请求资源不存在";
              break;
            case 500:
              errorMsg = "服务器内部错误(检查mysql或idea是否启动)";
              break;
            case 504:
              errorMsg = "网络超时";
              break;
            default:
              errorMsg = `连接错误: ${error.response.status}`;
              break;
          }
        } else {
          errorMsg = "连接到服务器失败";
        }
        ElMessage.error(errorMsg);
        return Promise.reject(error);
      }
    );
  }

  // GET 请求
  public get<T = Result>(url: string, params?: object): Promise<T> {
    return this.instance.get(url, { params });
  }

  // POST 请求
  public post<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.post(url, data);
  }

  // PUT 请求
  public put<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.put(url, data);
  }

  // DELETE 请求
  public delete<T = Result>(url: string): Promise<T> {
    return this.instance.delete(url);
  }
}

// 创建 HTTP 实例
export default new Http(config);
